﻿using System;
using System.Web;
using System.Web.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using WDA.Core;

namespace WDA.Web
{
	/// <summary>
	/// Http module (<see cref="IHttpModule"/> implementation) enabling access to WDAB services in web application.
	/// This module creates new <see cref="Services"/> instance for every request and ensures that this instance
	/// is released after request is processed.	
	/// </summary>
	public class WDAHttpModule : IHttpModule
	{
		#region Const
		internal const string ServicesInstanceKey = "917B878E-8C4C-447d-8098-AC198527A094";
		#endregion

		#region Fields
		private HttpApplication _context;
		private string _configName;
		private string _hostName;
		private string _unitySectionName;
		private string _containerName;
		#endregion

		#region IHttpModule Members
		public void Dispose()
		{

		}
		public void Init(HttpApplication context)
		{
			WDAHttpModuleConfigurationSection section = (WDAHttpModuleConfigurationSection)WebConfigurationManager.GetSection("wdaHttpModule");

			_configName = section.ConfigurationName;
			_hostName = section.HostName;
			_unitySectionName = section.UnitySectionName;
			_containerName = section.UnityContainerName;

			_context = context;
			_context.PreRequestHandlerExecute += PreRequestHandlerExecute;
			_context.PostRequestHandlerExecute += PostRequestHandlerExecute;
		}

		private static void PostRequestHandlerExecute(object sender, EventArgs e)
		{
			Services services = (Services)HttpContext.Current.Items[ServicesInstanceKey];
			services.Dispose();
		}

		private void PreRequestHandlerExecute(object sender, EventArgs e)
		{
			IUnityContainer container = new UnityContainer();
			UnityConfigurationSection section = (UnityConfigurationSection)WebConfigurationManager.GetSection(_unitySectionName);
			section.Containers[_containerName].Configure(container);

			Services services = new Services(container, _configName, _hostName, true);
			HttpContext.Current.Items[ServicesInstanceKey] = services;
		}
		#endregion
	}
}
